package com.yao.springredisdemo.service.impl;

import com.yao.springredisdemo.dao.StudentRepository;
import com.yao.springredisdemo.entity.Student;
import com.yao.springredisdemo.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 使用redisTemplate来操作redis，需要手动添加、删除、更改、查找缓存
 * 默认使用lettuce操作redis
 * lettuce主要用于分布式缓存框架，对redis提供的操作没有Jedis全
 * By default, all LettuceConnection instances created by the LettuceConnectionFactory share the same thread-safe native
 * connection for all non-blocking and non-transactional operations.To use a dedicated connection each time, set shareNativeConnection to false. LettuceConnectionFactory can also be configured to use a LettucePool
 * for pooling blocking and transactional connections or all connections if shareNativeConnection is set to false.
 *
 * 使用RedisTemplate是使用连接工厂创建连接
 * @author yao
 */
//@Service
@Slf4j
public class StudentServiceOneImpl implements StudentService {
    private StudentRepository studentRepository;
    private RedisTemplate<String, Student> redisTemplate;

    @Autowired
    public StudentServiceOneImpl(StudentRepository studentRepository, RedisTemplate<String, Student> redisTemplate) {
        this.studentRepository = studentRepository;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Student insertStudent(Student student) {
        // 插入数据库
        Student s = studentRepository.save(student);
        log.info("insert into h2 {}", student);
        // 插入redis
        redisTemplate.opsForValue().set(String.valueOf(student.getStudentId()), student);
        log.info("insert into redis {}", student);
        return s;
    }

    @Override
    public void deleteStudentById(Long id) {
        // 从数据库删除
        studentRepository.deleteById(id);
        log.info("delete from h2 id={}", id);
        // 从redis删除
        redisTemplate.delete(String.valueOf(id));
        log.info("delete from redis id={}", id);
    }

    @Override
    public Student selectStudentById(Long id) {
        // 从redis获取
        Student student = redisTemplate.opsForValue().get(String.valueOf(id));
        log.info("get from redis, {}", student);
        // redis为空从数据库获取
        if (student == null) {
            student = studentRepository.getOne(id);
            log.info("get from h2, {}", student);
        }
        return student;
    }
}
